/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.butler.cezary.syncTool.storage;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.logging.Logger;
import org.apache.commons.codec.binary.Base32;

/**
 *
 * @author Czarek
 */
public class CheckSumUtils {
    // <editor-fold defaultstate="collapsed" desc="Checksum calculation local fields">
    private static final Logger log = Logger.getLogger(CheckSumUtils.class.getName());

    private static final int BUF_LEN = 1024 * 1024;
    private final byte[] buffer = new byte[BUF_LEN];// </editor-fold>

    private static String byteArray2Hex(final byte[] hash) {
        final Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }

    //private 
    private String byteArray2Base32(final byte[] hash) {
        final Base32 b32codec = new Base32(256 / 32 * 5, new byte[]{});
        return b32codec.encodeToString(hash);
    }

    public String calclulateChecksum(File plik) {
        try {
            final FileInputStream stream = new FileInputStream(plik);
            try {
                md.reset();
                int len;
                do {
                    len = stream.read(buffer);
                    md.update(buffer);
                } while (len == BUF_LEN);
                return byteArray2Base32(md.digest());
            } finally {
                stream.close();
            }
        } catch (Exception e) {
            throw new RuntimeException("Unexpected exception", e);
        }

    }
    private final MessageDigest md;

    // <editor-fold defaultstate="collapsed" desc="MessageDigest static init">
    {
        MessageDigest localMd = null;
        try {
            localMd = MessageDigest.getInstance("SHA-1");

        } catch (NoSuchAlgorithmException ne) {
            log.severe("Nie udało się pobrać kodeka SHA-1");
        }
        md = localMd;
    }// </editor-fold>
}
